/*
 * Editor.java
 *
 * Created on 26 de Mar�o de 2007, 21:01
 */

package editorlabirinto;

import java.util.Enumeration;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
 *
 * @author  tschimuneck
 */
public class Editor extends javax.swing.JFrame
{
    /** Creates new form Editor */
    private Thing currentThing;
    private Thing mapa[][],menuThings[] = new Thing[15];
    private JLabel mapaLabels[][];
    private ThingPopupMenu popupMenu;
    private ToolWindow toolWindow;
    private Thing person;
    private Thing person2;
    private boolean moving;
    private int movingX,movingY;
    
    private ImageIcon imgFundo;
    
    private GridCanvas grid;
    
    public Editor()
    {
//     //   this.grid = new GridCanvas();
        ///       this.getContentPane().add(this.grid);
        //    this.grid.setBounds(0,0,640,480);
        initComponents();
        //this.paFundo.setLocation(this.getInsets().left,this.getInsets().top);
        this.imgFundo = new ImageIcon(this.getClass().getResource("/fundo1.png"));
        this.paFundo.setSize(640,480);
        this.paFundo.setOpaque(true);
        this.paFundo.setBackground(new Color(0,0,255));
        this.setSize(this.paFundo.getWidth()+this.getInsets().left+this.getInsets().right,this.paFundo.getHeight()+this.getInsets().top+this.getInsets().bottom);
        this.mapa = new Thing[20][15];
        this.mapaLabels = new JLabel[20][15];
        this.popupMenu = new ThingPopupMenu();
        this.moving = false;
        this.person = this.mapa[10][7] = new Thing();
        this.person.setId('P');
        this.person.setStopLeftIcon(new ImageIcon(this.getClass().getResource("/mario/stopLeft.gif")));
        this.person.setStopRightIcon(new ImageIcon(this.getClass().getResource("/mario/stopRight.gif")));
        this.person2 = this.mapa[10][8] = new Thing();
        this.person2.setId('2');
        this.person2.setStopLeftIcon(new ImageIcon(this.getClass().getResource("/mario/stopLeft2.gif")));
        this.person2.setStopRightIcon(new ImageIcon(this.getClass().getResource("/mario/stopRight2.gif")));
        JLabel jPerson = this.mapaLabels[10][7] = new JLabel();
        jPerson.setSize(32,32);
        jPerson.setLocation(320,32*7);
        jPerson.setIcon(this.person.getStopLeftIcon());
        JLabel jPerson2 = this.mapaLabels[10][8] = new JLabel();
        jPerson2.setSize(32,32);
        jPerson2.setLocation(320,32*8);
        jPerson2.setIcon(this.person2.getStopLeftIcon());
        this.paFundo.add(jPerson);
        this.paFundo.add(jPerson2);
        this.getContentPane().remove(this.paFundo);
        this.getContentPane().add(this.paFundo);
        this.paFundo.setBounds(0,0,640,480);
    }
    
    public void setToolWindow(ToolWindow toolWindow)
    {
        this.toolWindow = toolWindow;
        ThingButton btn;
        /*-------------------------------------------------------------
         * Aqui montamos os tipo de objetos que podem existir
         *-------------------------------------------------------------
         */
        Thing myThing = new Thing();
        myThing.setId('A'); /* Setar o ID */
        this.toolWindow.paThings.add(btn = new ThingButton());
        btn.setIcon(new ImageIcon(this.getClass().getResource("/madeira.jpg")));
        this.btnGroup.add(btn);
        btn.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnThingActionPerformed(evt);
            }
        });
        btn.setThing(myThing);
        myThing.setStopLeftIcon(btn.getIcon());
        myThing.setStopRightIcon(btn.getIcon());
        myThing.setIsConcrete(true);
        this.menuThings[0] = myThing;
        
        myThing = new Thing();
        myThing.setId('B'); /* Setar o ID */
        this.toolWindow.paThings.add(btn = new ThingButton());
        btn.setIcon(new ImageIcon(this.getClass().getResource("/redbox.gif")));
        this.btnGroup.add(btn);
        btn.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnThingActionPerformed(evt);
            }
        });
        btn.setThing(myThing);
        myThing.setStopLeftIcon(btn.getIcon());
        myThing.setStopRightIcon(btn.getIcon());
        myThing.setIsItem(true);
        myThing.setSpecialItem(Thing.SPECIAL_ITEM.UpLife);
        this.menuThings[1] = myThing;
        
        myThing = new Thing();
        myThing.setId('C'); /* Setar o ID */
        this.toolWindow.paThings.add(btn = new ThingButton());
        btn.setIcon(new ImageIcon(this.getClass().getResource("/fire.gif")));
        btn.setSelectedIcon(btn.getIcon());
        this.btnGroup.add(btn);
        btn.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnThingActionPerformed(evt);
            }
        });
        btn.setThing(myThing);
        myThing.setStopLeftIcon(btn.getIcon());
        myThing.setStopRightIcon(btn.getIcon());
        myThing.setIsOpponent(true);
        myThing.setOpponentType(Thing.OPPONENT_TYPE.Static);
        this.menuThings[2] = myThing;

        myThing = new Thing();
        myThing.setId('D'); /* Setar o ID */
        this.toolWindow.paThings.add(btn = new ThingButton());
        btn.setIcon(new ImageIcon(this.getClass().getResource("/door.gif")));
        btn.setSelectedIcon(btn.getIcon());
        this.btnGroup.add(btn);
        btn.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnThingActionPerformed(evt);
            }
        });
        btn.setThing(myThing);
        myThing.setStopLeftIcon(btn.getIcon());
        myThing.setStopRightIcon(btn.getIcon());
        myThing.setIsDoor(true);
        this.menuThings[3] = myThing;

        myThing = new Thing();
        myThing.setId('E'); /* Setar o ID */
        this.toolWindow.paThings.add(btn = new ThingButton());
        btn.setIcon(new ImageIcon(this.getClass().getResource("/anishellcreeper.gif")));
        btn.setSelectedIcon(btn.getIcon());
        this.btnGroup.add(btn);
        btn.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnThingActionPerformed(evt);
            }
        });
        btn.setThing(myThing);
        myThing.setStopLeftIcon(btn.getIcon());
        myThing.setStopRightIcon(btn.getIcon());
        myThing.setIsDoor(true);
        this.menuThings[4] = myThing;        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">//GEN-BEGIN:initComponents
    private void initComponents() {
        btnGroup = new javax.swing.ButtonGroup();
        paFundo = new javax.swing.JPanel();
        mbPrincipal = new javax.swing.JMenuBar();
        mnuArquivo = new javax.swing.JMenu();
        miAbrir = new javax.swing.JMenuItem();
        miSalvar = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        miSair = new javax.swing.JMenuItem();
        mnuAjuda = new javax.swing.JMenu();
        miSobre = new javax.swing.JMenuItem();

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        paFundo.setLayout(null);

        paFundo.setBackground(new java.awt.Color(51, 51, 255));
        paFundo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onPaFundoMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                onPaFundoMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                onPaFundoMouseReleased(evt);
            }
        });
        paFundo.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                onPaFundoMouseDragged(evt);
            }
        });

        getContentPane().add(paFundo);
        paFundo.setBounds(0, 0, 160, 140);

        mnuArquivo.setMnemonic('A');
        mnuArquivo.setText("Arquivo");
        miAbrir.setMnemonic('b');
        miAbrir.setText("Abrir");
        miAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miAbrirActionPerformed(evt);
            }
        });

        mnuArquivo.add(miAbrir);

        miSalvar.setMnemonic('S');
        miSalvar.setText("Salvar");
        miSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSalvarActionPerformed(evt);
            }
        });

        mnuArquivo.add(miSalvar);

        mnuArquivo.add(jSeparator1);

        miSair.setMnemonic('r');
        miSair.setText("Sair");
        miSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSairActionPerformed(evt);
            }
        });

        mnuArquivo.add(miSair);

        mbPrincipal.add(mnuArquivo);

        mnuAjuda.setMnemonic('u');
        mnuAjuda.setText("Ajuda");
        miSobre.setText("Item");
        mnuAjuda.add(miSobre);

        mbPrincipal.add(mnuAjuda);

        setJMenuBar(mbPrincipal);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void miSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSairActionPerformed
// TODO adicione seu código de manipulação aqui:
        System.exit(0);
    }//GEN-LAST:event_miSairActionPerformed
    
    private void miSalvarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_miSalvarActionPerformed
    {//GEN-HEADEREND:event_miSalvarActionPerformed
// TODO adicione seu c�digo de manipula��o aqui:
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new MapaFileFilter());
        if (chooser.showSaveDialog(this) == JFileChooser.CANCEL_OPTION)
        {
            JOptionPane.showMessageDialog(this,"Cancelou");
        }
        else
        {
            String gravar="";
            for(int lin=0;lin<15;lin++)
            {
                for(int col=0;col<20;col++)
                {
                    if (this.mapa[col][lin] != null)
                    {
                        gravar += this.mapa[col][lin].getId();
                    }
                    else
                    {
                        gravar += ' ';
                    }
                }
                gravar += '\n';
            }
            if (!Editor.GravaArquivo(chooser.getSelectedFile().getAbsolutePath(),gravar))
            {
                JOptionPane.showMessageDialog(this,"Erro ao gravar arquivo do mapa!");
            }
        }
    }//GEN-LAST:event_miSalvarActionPerformed
    
    private void onPaFundoMouseReleased(java.awt.event.MouseEvent evt)//GEN-FIRST:event_onPaFundoMouseReleased
    {//GEN-HEADEREND:event_onPaFundoMouseReleased
// TODO add your handling code here:
        if (this.moving)
        {
            int x = (int)(evt.getX() / 32);
            int y = (int)(evt.getY() / 32);
            JLabel l = this.mapaLabels[x][y];
            Thing  t = this.mapa[x][y];
            this.mapaLabels[x][y] = this.mapaLabels[this.movingX][this.movingY];
            this.mapa[x][y] = this.mapa[this.movingX][this.movingY];
            this.mapaLabels[this.movingX][this.movingY] = l;
            this.mapa[this.movingX][this.movingY] = t;
            this.moving = false;
            if (this.mapaLabels[this.movingX][this.movingY] != null)
            {
                this.mapaLabels[this.movingX][this.movingY].setLocation(32 * this.movingX,32 * this.movingY);
            }
            if (this.mapaLabels[x][y] != null)
            {
                this.mapaLabels[x][y].setLocation(32 * x,32 * y);
            }
            
        }
    }//GEN-LAST:event_onPaFundoMouseReleased
    
    private void onPaFundoMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_onPaFundoMouseClicked
    {//GEN-HEADEREND:event_onPaFundoMouseClicked
// TODO add your handling code here:
        this.onPaFundoMouseDragged(evt);
    }//GEN-LAST:event_onPaFundoMouseClicked
    
    private void onPaFundoMouseDragged(java.awt.event.MouseEvent evt)//GEN-FIRST:event_onPaFundoMouseDragged
    {//GEN-HEADEREND:event_onPaFundoMouseDragged
// TODO add your handling code here:
        int x = (int)(evt.getX() / 32);
        int y = (int)(evt.getY() / 32);
        if (this.moving)
        {
            this.mapaLabels[this.movingX][this.movingY].setLocation(evt.getPoint());
        }
        else if (this.mapa[x][y] == null)
        {
            Thing tgNovaPeca = this.currentThing.clone();
            this.mapa[x][y] = tgNovaPeca;
            JLabel g = new JLabel();
            g.setIcon(tgNovaPeca.getStopLeftIcon());
            g.setSize(32,32);
            this.mapaLabels[x][y] = g;
            this.paFundo.add(g);
            g.setLocation(x*32,y*32);
            this.paFundo.repaint();
        }
    }//GEN-LAST:event_onPaFundoMouseDragged
    
    public void setThing(Thing thing)
    {
        this.currentThing = thing;
    }
    
    private void onPaFundoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onPaFundoMousePressed
// TODO adicione seu c�digo de manipula��o aqui:
        int x = (int)(evt.getX() / 32);
        int y = (int)(evt.getY() / 32);
        if (this.mapa[x][y] != null && evt.getButton() == java.awt.event.MouseEvent.BUTTON3)
        {
            this.popupMenu.setThing(this.mapa[x][y]);
            this.popupMenu.setMapa(this.mapa);
            this.popupMenu.setMapaLabels(this.mapaLabels);
            this.popupMenu.setXY(x,y);
            this.popupMenu.show( evt.getComponent(),evt.getX(), evt.getY() );
        }
        else if (this.mapa[x][y] != null && evt.getButton() == java.awt.event.MouseEvent.BUTTON1)
        {
            this.movingX = x;
            this.movingY = y;
            this.moving = true;
        }
        
    }//GEN-LAST:event_onPaFundoMousePressed
    
    private void miAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miAbrirActionPerformed
// TODO adicione seu c�digo de manipula��o aqui:
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new MapaFileFilter());
        if (chooser.showOpenDialog(this) == JFileChooser.CANCEL_OPTION)
        {
            JOptionPane.showMessageDialog(this,"Cancelou");
        }
        else
        {
            if (!this.LeArquivoMapa(chooser.getSelectedFile().getAbsolutePath()))
            {
                JOptionPane.showMessageDialog(this,"Erro lendo o mapa!");
            }
        }
        
    }//GEN-LAST:event_miAbrirActionPerformed
    
    /**
     * @param args the command line arguments
     */
    
    public void btnThingActionPerformed(java.awt.event.ActionEvent evt)
    {
        ThingButton btn = (ThingButton)evt.getSource();
        this.currentThing = btn.getThing();
    }
    
    private static boolean GravaArquivo(String nome,String conteudo)
    {
        File fArquivo = new File(nome);
        Writer wDestino = null;
        boolean result = true;
        try
        {
            
            wDestino = new BufferedWriter(new FileWriter(nome));
            wDestino.write(conteudo);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            result = false;
        }
        finally
        {
            try
            {
                if (wDestino!= null)wDestino.close();
                result = true;
            }
            catch(Exception e)
            { result = false; }
        }
        return result;
    }
    
    private boolean LeArquivoMapa(String nome)
    {
        BufferedReader bfArquivo = null;
        boolean result = true;
        try
        {
            bfArquivo = new BufferedReader(new FileReader(nome));
            String sLinha = null;
            int j = 0; // Linha
            while ((sLinha=bfArquivo.readLine())!=null)
            {
                System.out.println(sLinha);
                for (int i=0;i<sLinha.length();i++)
                {
                    for(int k=0;k<this.menuThings.length;k++)
                    {
                        Thing t = this.menuThings[k];
                        if (t==null)
                        {
                            continue;
                        }
                        System.out.println("Vem da barra: "+t.getId());
                        if (sLinha.charAt(i) == 'P')
                        {
                            if (this.mapaLabels[i][j] != null)
                            {
                                this.paFundo.remove(this.mapaLabels[i][j]);
                            }
                            this.person = this.mapa[i][j] = new Thing();
                            this.person.setId('P');
                            this.person.setStopLeftIcon(new ImageIcon(this.getClass().getResource("/mario/stopLeft.gif")));
                            this.person.setStopRightIcon(new ImageIcon(this.getClass().getResource("/mario/stopRight.gif")));
                            JLabel jPerson = this.mapaLabels[i][j] = new JLabel();
                            jPerson.setSize(32,32);
                            jPerson.setLocation(32*i,32*j);
                            jPerson.setIcon(this.person.getStopLeftIcon());
                            this.paFundo.add(jPerson);
                            break;
                        }
                        else if (t.getId() == sLinha.charAt(i))
                        {
                            if (sLinha.charAt(i)=='C')
                            {
                                System.out.println("Naum t� intendiendo....");
                            }
                            Thing tgNovaPeca = this.mapa[i][j] = t.clone();
                            JLabel g = new JLabel();
                            g.setIcon(tgNovaPeca.getStopLeftIcon());
                            g.setSize(32,32);
                            if (this.mapaLabels[i][j] != null)
                            {
                                this.paFundo.remove(this.mapaLabels[i][j]);
                            }
                            this.mapaLabels[i][j] = g;
                            this.paFundo.add(g);
                            g.setLocation(i*32,j*32);
                            break;
                        }
                        if (this.mapaLabels[i][j] != null)
                        {
                            this.paFundo.remove(this.mapaLabels[i][j]);
                        }
                        this.mapaLabels[i][j] = null;
                        this.mapa[i][j] = null;
                    }
                }
                j++;
            }
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            result=false;
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
            result=false;
        }
        finally
        {
            try
            {
                if (bfArquivo!= null)
                {
                    bfArquivo.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
                result=false;
            }
        }
        this.paFundo.repaint();
        return result;
    }
    
    // Declaração de variáveis - não modifique//GEN-BEGIN:variables
    private javax.swing.ButtonGroup btnGroup;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuBar mbPrincipal;
    private javax.swing.JMenuItem miAbrir;
    private javax.swing.JMenuItem miSair;
    private javax.swing.JMenuItem miSalvar;
    private javax.swing.JMenuItem miSobre;
    private javax.swing.JMenu mnuAjuda;
    private javax.swing.JMenu mnuArquivo;
    private javax.swing.JPanel paFundo;
    // Fim da declaração de variáveis//GEN-END:variables
    
}
